#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int main()
{
    // 1.创建管道
    int fds[2] = {0};
    int n = pipe(fds); // fds输出型参数
    if (n != 0)
    {
        cerr << "pipe error" << endl;
        return 1;
    }

    // 2.创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程 写入 关闭读端
        // 3.关闭不需要的fd
        // 使用全局的函数 这里相当于使用系统调用 方便观察
        ::close(fds[0]);

        int cnt = 0;
        int total = 0;
        while (true)
        {
            string message = "h";
            // message += to_string(getpid());
            // message += ", ";
            // message += to_string(cnt);

            // fds[1]
            total += ::write(fds[1], message.c_str(), message.size());
            cnt++;
            cout << "total:" << total << endl;
            sleep(1);
            // break;
        }

        ::close(fds[1]);
        exit(0);
    }
    else
    {
        // 父进程 读取 关闭写端
        // 3.关闭不需要的fd
        ::close(fds[1]);

        // fds[0]
        char buffer[1024];
        while (true)
        {
            sleep(1);
            ssize_t n = ::read(fds[0], buffer, 1024);
            if (n > 0) // 读取成功
            {
                buffer[n] = 0; // 因为是C语言
                cout << "child->father, message:" << buffer << endl;
            }
            else if (n == 0)
            {
                cout << "n:" << n << endl;
                cout << "child quit ??? me too" << endl;
                break;
            }
            ::close(fds[0]); //关闭读端
            break; // 读一条语句直接break
            cout << endl;
        }

        int status = 0;
        pid_t rid = waitpid(id, &status, 0); // 阻塞等待
        cout << "father wait child success:" << rid << ", exit code:" << ((status >> 8) & 0xFF) <<
        ", exit signal:" << (status & 0x7F) << endl;
    }
    return 0;
}
